using System.Reflection;

namespace HandyControlUIDemo.tools;

public static class ReflectUtils
{
    /// <summary>
    /// 通过反射获取对象中的私有字段
    /// </summary>
    /// <param name="obj">对象实例</param>
    /// <param name="fieldName">字段名称</param>
    /// <returns>字段值</returns>
    public static T? GetPrivateField<T>(object obj, string fieldName) where T : class
    {
        FieldInfo? fieldInfo = obj.GetType().GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
        if (fieldInfo != null)
        {
            var fieldValue = fieldInfo.GetValue(obj);
            return fieldValue as T;
        }

        return default;
    }
}